<template>
	<WithFixedPageContainer v-model:page="page">
		<!-- 页签 -->
		<el-tabs v-model="activeTab" @tab-click="handleTabChange">
			<el-tab-pane
				v-for="tab in tabs"
				:key="tab.key"
				:label="tab.label"
				:name="tab.key"
			/>
		</el-tabs>

		<!-- 查询表单 -->
		<div class="bg-white p-2 rounded-md">
			<BasicTableFrom :formList="formList" @search="handleSearch">
				<template #menu>
					<el-button type="primary" @click="handleExport">导出</el-button>
				</template>
			</BasicTableFrom>
		</div>

		<!-- 运单表格 -->
		<div class="bg-white p-2 rounded-md">
			<BasicTable :data="tableData" :option="tableColumns">
				<template #menu="{ row }">
					<el-button text type="primary" @click="handleDetail(row)"
						>详情</el-button
					>
					<template v-if="row.status === '待接单'">
						<el-button text type="primary" @click="handleEdit(row)"
							>编辑</el-button
						>
						<el-button text type="danger" @click="handleCancel(row)"
							>取消调度</el-button
						>
					</template>
					<template v-else-if="row.status === '待提货'">
						<el-button text type="danger" @click="handleCancel(row)"
							>取消调度</el-button
						>
					</template>
					<template v-else-if="row.status === '异常'">
						<el-button text type="danger" @click="handleEditException(row)"
							>异常修改</el-button
						>
					</template>
				</template>
			</BasicTable>
		</div>
		<!-- 详情/编辑弹窗等 -->
		<WaybillEditDialog ref="waybillEditDialogRef" />
		<WaybillDetail ref="waybillDetailRef" />
	</WithFixedPageContainer>
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus';
import { ref, computed } from 'vue';
import exportFile from '/@/utils/exportFile';
import WaybillEditDialog from './components/WaybillEditDialog.vue';
import WaybillDetail from './components/WaybillDetail.vue';
const waybillEditDialogRef = ref();
const waybillDetailRef = ref();
// 查询表单配置
const formList = computed((): BasicTableNameSpace.FormItemType[] => [
	{
		key: 'dateRange',
		type: 'daterange',
		label: '下单日期',
		startPlaceholder: '开始日期',
		endPlaceholder: '结束日期',
		valueFormate: 'YYYY-MM-DD',
	},
	{
		key: 'origin',
		type: 'input-text',
		label: '始发地',
		placeholder: '始发地',
		clearable: true,
	},
	{
		key: 'destination',
		type: 'input-text',
		label: '目的地',
		placeholder: '目的地',
		clearable: true,
	},
	{
		key: 'keyword',
		type: 'input-text',
		label: '关键字',
		placeholder: '车牌号/运企/司机/运单号',
		clearable: true,
	},
]);

// 原始数据
const allData = ref([
	{
		waybillNo: 'YD202505010001',
		origin: '成都',
		destination: '重庆（璧山）',
		company: 'XXXX运输有限公司',
		driver: '张三',
		phone: '135XXXXXXXX',
		plateNo: '川A00515D',
		chargeType: '单趟计费',
		totalFee: 200,
		planDepartTime: '2025-05-01 06:20:00',
		planArriveTime: '2025-05-01 09:20:00',
		actualDepartTime: '2025-04-30 20:30:11',
		actualArriveTime: '',
		creator: '管理员',
		createTime: '2025-04-30 18:30:11',
		status: '待接单',
	},
	{
		waybillNo: 'YD202505010002',
		origin: '成都',
		destination: '重庆（江北）',
		company: 'XXXX运输有限公司',
		driver: '李四',
		phone: '136XXXXXXXX',
		plateNo: '川A00596D',
		chargeType: '单趟计费',
		totalFee: 220,
		planDepartTime: '2025-05-02 08:00:00',
		planArriveTime: '2025-05-02 12:00:00',
		actualDepartTime: '',
		actualArriveTime: '',
		creator: '管理员',
		createTime: '2025-04-30 19:00:00',
		status: '待提货',
	},
	{
		waybillNo: 'YD202505010003',
		origin: '成都',
		destination: '重庆（渝北）',
		company: 'XXXX运输有限公司',
		driver: '王五',
		phone: '137XXXXXXXX',
		plateNo: '川A00666D',
		chargeType: '单趟计费',
		totalFee: 250,
		planDepartTime: '2025-05-03 09:00:00',
		planArriveTime: '2025-05-03 13:00:00',
		actualDepartTime: '2025-05-03 09:10:00',
		actualArriveTime: '',
		creator: '管理员',
		createTime: '2025-05-01 10:00:00',
		status: '运输中',
	},
	{
		waybillNo: 'YD202505010004',
		origin: '成都',
		destination: '重庆（南岸）',
		company: 'XXXX运输有限公司',
		driver: '赵六',
		phone: '138XXXXXXXX',
		plateNo: '川A00777D',
		chargeType: '单趟计费',
		totalFee: 230,
		planDepartTime: '2025-05-04 10:00:00',
		planArriveTime: '2025-05-04 14:00:00',
		actualDepartTime: '2025-05-04 10:05:00',
		actualArriveTime: '2025-05-04 14:10:00',
		creator: '管理员',
		createTime: '2025-05-02 11:00:00',
		status: '已签收',
	},
	{
		waybillNo: 'YD202505010005',
		origin: '成都',
		destination: '重庆（沙坪坝）',
		company: 'XXXX运输有限公司',
		driver: '孙七',
		phone: '139XXXXXXXX',
		plateNo: '川A00888D',
		chargeType: '单趟计费',
		totalFee: 210,
		planDepartTime: '2025-05-05 11:00:00',
		planArriveTime: '2025-05-05 15:00:00',
		actualDepartTime: '',
		actualArriveTime: '',
		creator: '管理员',
		createTime: '2025-05-03 12:00:00',
		status: '异常',
	},
]);

// 统计各状态数量
const statusCount = computed(() => {
	const countMap: Record<string, number> = {
		all: allData.value.length,
		pending: 0,
		toPickup: 0,
		inTransit: 0,
		signed: 0,
		completed: 0,
		cancelled: 0,
		rejected: 0,
		exception: 0,
	};
	allData.value.forEach((item) => {
		switch (item.status) {
			case '待接单':
				countMap.pending++;
				break;
			case '待提货':
				countMap.toPickup++;
				break;
			case '运输中':
				countMap.inTransit++;
				break;
			case '已签收':
				countMap.signed++;
				break;
			case '已完成':
				countMap.completed++;
				break;
			case '已取消':
				countMap.cancelled++;
				break;
			case '已拒绝':
				countMap.rejected++;
				break;
			case '异常':
				countMap.exception++;
				break;
		}
	});
	return countMap;
});

// 页签配置（带数量）
const tabs = computed(() => [
	{ key: 'all', label: `全部(${statusCount.value.all})` },
	{ key: 'pending', label: `待接单(${statusCount.value.pending})` },
	{ key: 'toPickup', label: `待提货(${statusCount.value.toPickup})` },
	{ key: 'inTransit', label: `运输中(${statusCount.value.inTransit})` },
	{ key: 'signed', label: `已签收(${statusCount.value.signed})` },
	{ key: 'completed', label: `已完成(${statusCount.value.completed})` },
	{ key: 'cancelled', label: `已取消(${statusCount.value.cancelled})` },
	{ key: 'rejected', label: `已拒绝(${statusCount.value.rejected})` },
	{ key: 'exception', label: `异常(${statusCount.value.exception})` },
]);

const activeTab = ref('all');

// 表格数据根据页签过滤
const tableData = computed(() => {
	if (activeTab.value === 'all') return allData.value;
	const statusMap: Record<string, string> = {
		pending: '待接单',
		toPickup: '待提货',
		inTransit: '运输中',
		signed: '已签收',
		completed: '已完成',
		cancelled: '已取消',
		rejected: '已拒绝',
		exception: '异常',
	};
	return allData.value.filter(
		(item) => item.status === statusMap[activeTab.value],
	);
});

const page = ref({
	pageSize: 30,
	pageNum: 1,
	total: 0,
	currentPage: 1,
});
const loading = ref(false);

const companyList = ref([{ id: '1', name: 'XXXX运输有限公司' }]);
const driverList = ref([
	{ id: 'd1', name: '司机1', phone: '13543434343', defaultCarNo: '川A00515D' },
]);
const carList = ref([{ no: '川A00515D' }]);

function handleTabChange() {
	handleSearch();
}
function handleSearch(data?: any) {
	// TODO: 查询接口
	// data为表单数据
	console.log('search', data, activeTab.value);
}
function handleExport() {
	const exportData = {
		// 表头配置
		headers: [
			{ title: '运单号', key: 'waybillNo' },
			{ title: '始发地', key: 'origin' },
			{ title: '目的地', key: 'destination' },
			{ title: '状态', key: 'status' },
			{ title: '运企名称', key: 'company' },
			{ title: '司机', key: 'driver' },
			{ title: '联系电话', key: 'phone' },
			{ title: '车牌号', key: 'plateNo' },
			{ title: '计费方式', key: 'chargeType' },
			{ title: '运费合计(元)', key: 'totalFee' },
			{ title: '计划发车时间', key: 'planDepartTime' },
			{ title: '计划到达时间', key: 'planArriveTime' },
			{ title: '实际发车时间', key: 'actualDepartTime' },
			{ title: '实际到达时间', key: 'actualArriveTime' },
			{ title: '创建人', key: 'creator' },
			{ title: '创建时间', key: 'createTime' },
		],
		// 数据
		data: tableData.value,
		// 文件名
		filename: `运单列表_${new Date().toLocaleDateString()}`,
	};

	exportFile(exportData);
}
function handleDetail(row: any) {
	// 显示详情弹窗
	waybillDetailRef.value?.open(row);
}
function handleEdit(row: any) {
	waybillEditDialogRef.value?.open({
		waybill: row,
		companyList: companyList.value,
		driverList: driverList.value,
		carList: carList.value,
	});
}
function handleEditException(row: any) {
	handleEdit(row);
}
function handleCancel(row: any) {
	ElMessageBox.confirm(
		'确定要取消该条运单的调度？取消后将不能进行后续的司机接单、运输操作',
		'提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		},
	).then(() => {
		// TODO: 取消调度
		console.log('取消调度', row);
	});
}

// 表格列配置
const tableColumns = {
	index: true,
	menuWidth: 220,
	hiddenPage: true,
	column: [
		{ label: '运单号', prop: 'waybillNo', width: 140 },
		{ label: '始发地', prop: 'origin', width: 120, overHidden: true },
		{ label: '目的地', prop: 'destination', width: 120, overHidden: true },
		{ label: '状态', prop: 'status' },
		{ label: '运企名称', prop: 'company', width: 140, overHidden: true },
		{ label: '司机', prop: 'driver' },
		{ label: '联系电话', prop: 'phone', width: 120, overHidden: true },
		{ label: '车牌号', prop: 'plateNo', width: 120 },
		{ label: '计费方式', prop: 'chargeType', width: 120 },
		{ label: '运费合计(元)', prop: 'totalFee', width: 120 },
		{ label: '计划发车时间', prop: 'planDepartTime', width: 160 },
		{ label: '计划到达时间', prop: 'planArriveTime', width: 160 },
		{ label: '实际发车时间', prop: 'actualDepartTime', width: 160 },
		{ label: '实际到达时间', prop: 'actualArriveTime', width: 160 },
		{ label: '创建人', prop: 'creator' },
		{ label: '创建时间', prop: 'createTime', width: 160 },
	],
};
</script>

<style lang="scss" scoped>
.mb-2 {
	margin-bottom: 16px;
}
</style>
